// import query from '@dfeidao/atom-nodejs/db/query';
import sql_query from '@dfeidao/atom-nodejs/db/sql-query';
import format from '@dfeidao/atom-nodejs/dt/format';
import log from '@dfeidao/atom-nodejs/logger/log';
import send_msg from '@dfeidao/send-msg/nodejs';

// import get_user_by_usercode from '@dfeidao/atom-nodejs/msg/get-user-by-usercode';

import { IncomingHttpHeaders } from 'http';


import { productid, systemid } from '../atom/config';

interface Message {
	sort: {
		[key: string]: 1 | -1;
	};
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:app-equip_list/s001,action_id:' + action_id);

	const asc = [];
	const desc = [];
	if (message.sort) {
		const key = Object.keys(message.sort)[0];
		if (message.sort[key] === -1) {
			desc.push(key);
		} else if (message.sort[key] === 1) {
			asc.push(key);
		}
	}

	// equip_online_history
	// equipment        // 设备
	// is_online        是否在线 boolean 50 √ ⅹ
	// equip_no         设备编号 string 50 √ ⅹ
	// gather_time      检测时间 timestamp 50 √ ⅹ
	// arrive_time      上线时间

	// const { exec, prepare } = query(action_id, session_id,  systemid);
	// prepare('equipment', ['_id', 'equip_no', 'equip_name'], {});
	// // 根据usercode获取companyid
	// const [equip] = await exec();
	const sql = `
	select _id,equip_no,equip_name from equipment;
	`;
	const equip = await sql_query<{
		Date: string;
		state: string;
		equip_no: string;
	}>(action_id, session_id, systemid, productid, sql, 'postgre');

	const e_nos = equip.map((item) => {
		return item.equip_no;
	});

	const _state = await send_msg({ actionid: action_id, sessionid: session_id }, 'loginservice.getusersessionsbyusercode', {
		productid,
		usercode: e_nos
	}) as { result: string, code: number };
	const state = JSON.parse(_state.result);


	// const state = await get_user_by_usercode(action_id, session_id, 'self_sell', 'self_sell', e_nos);

	console.log(e_nos, '1111111111111111111111');
	console.log(state, '22222222222222222222222');

	e_nos.forEach((item: string, i: number) => {

		console.log(state[item], '33333333333333');
		console.log(state[item].length, '4444444444444');
		if (state[item].length > 0) {
			const time = state[item][0].lastReplyTime;
			equip[i].Date = format(time, '2');
			equip[i].state = '在线';
		} else {
			equip[i].Date = '';
			equip[i].state = '离线';
		}
	});

	log('Service end path:app-equip_list/s001,action_id:' + action_id);
	return {
		data: equip
	};
}
